<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>角色管理</title>
    <link rel="stylesheet" href="../../lib/element-ui/theme-chalk/index.css">
    <link rel="stylesheet" href="../../lib/vxe-table/index.css">
    <link rel="stylesheet" href="../../lib/vxe-table-plugin-element/style.css">
    <link rel="stylesheet" href="../../lib/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="../../static/css/skins.css">
    <script type="text/javascript" src="../../lib/vue/vue.js"></script>
    <script type="text/javascript" src="../../lib/xe-utils/xe-utils.js"></script>
    <script type="text/javascript" src="../../lib/element-ui/index.js"></script>
    <script type="text/javascript" src="../../lib/vxe-table/index.js"></script>
    <script type="text/javascript" src="../../lib/vxe-table-plugin-element/index.js"></script>
    <script type="text/javascript" src="../../lib/xlsx/xlsx.full.min.js"></script>
    <script type="text/javascript" src="../../lib/vxe-table-plugin-export-xlsx/index.min.js"></script>
    <script type="text/javascript" src="../../lib/xe-ajax/xe-ajax.js"></script>
    <script type="text/javascript" src="../../static/js/jquery.min.js"></script>
    <script type="text/javascript" src="../../static/js/webApi.js"></script>
    <script type="text/javascript" src="../../static/js/tool.js"></script>
    <style type="text/css">
        /*
            找到html标签、body标签，和挂载的标签
            都给他们统一设置样式
        */
        html,
        body,
        #app,
        .el-container {
            /*设置内部填充为0，几个布局元素之间没有间距*/
            padding: 0px;
            /*外部间距也是如此设置*/
            margin: 0px;
            /*统一设置高度为100%*/
            height: 100%;
        }

        .el-main {
            padding: 4px;
        }
		.el-icon-search{
			color: #409EFF;
		}
		.el-icon-refresh-right{
			color: #409EFF;
		}
        [v-cloak] {
            display: none;
        }
    </style>
</head>

<body class="skin-blue">
    <el-container id="app" v-cloak>
        <el-main>
            <el-form :inline="true" :model="queryData" ref="queryData" label-width="80px" label-position="right"
                size="mini" style="height: 35px" @submit.native.prevent>
                <el-form-item label="角色名称">
                    <el-input v-model="queryData.keyword" placeholder="请输入关键字"></el-input>
                </el-form-item>
				<el-form-item>
				    <el-button size="mini" icon="el-icon-search" @click="searchEvent">查询</el-button>
				    <el-button size="mini" icon="el-icon-refresh-right" @click="searchEventA">重置</el-button>
				</el-form-item>
            </el-form>

            <vxe-grid border ref="xGrid" @page-change="handlePageChange" resizable show-overflow
                highlight-current-row="true" keep-source :height="tableHeight" size="mini" :checkbox-config="tableRadio"
                :pager-config="tablePage" :data="tableData" :header-cell-style="{'text-align':'center'}"
                :loading="dataLoading" :toolbar="tableToolbar" :export-config="tableExport"
                @cell-dblclick="cellDBLClickEvent" :edit-config="{trigger:'click', mode:'row'}"
                @toolbar-button-click="toolbarButtonClickEvent" :sort-config="{remot:true}" @sort-change="tableSortChange">
                <vxe-table-column type="checkbox" width="60" align="center"></vxe-table-column>
                <vxe-table-column type="seq" title="序号" width="60" align="right">
                </vxe-table-column>
                <vxe-table-column field="roleId" title="角色代码" width="110" align="right" sortable='custom'>
                </vxe-table-column>
                <vxe-table-column field="roleName" title="角色名称" align="left">
                </vxe-table-column>
                <vxe-table-column field="parentRoleName" title="父级角色" align="left">
                </vxe-table-column>
                <vxe-table-column field="roleDsc" title="备注" align="left">
                </vxe-table-column>
                <vxe-table-column field="createUser" title="创建人" width="130" align="left">
                </vxe-table-column>
                <vxe-table-column field="createTime" title="创建日期" width="150" align="right" :formatter="formatDate">
                </vxe-table-column>
                <vxe-table-column field="parentRoleId" title="父级角色ID" align="right" :visible="visible">
                </vxe-table-column>
                <vxe-table-column field="roleId" title="角色ID" align="right" :visible="visible">
                </vxe-table-column>
            </vxe-grid>

            <vxe-modal ref="xModal" v-model="showEdit" :title="selectRow ? '编辑&保存' :'新增&保存'" width="800"
                :loading="submitLoading" resize destroy-on-close>
                <el-form :model="formData" :rules="formRules" ref="formData" label-width="80px" label-position="right"
                    size="mini">
                    <template v-if="visible===true">
                        <el-form-item label="角色ID" prop="roleId">
                            <el-input v-model="formData.roleId"></el-input>
                        </el-form-item>
                    </template>
                    <el-form-item label="角色名称" prop="roleName">
                        <el-input type="text" v-model="formData.roleName" placeholder="请输入角色名称" maxlength="200"
                            show-word-limit></el-input>
                    </el-form-item>
                    <el-form-item label="父级角色" prop="parentRoleId">
                        <el-cascader v-model="formData.parentRoleId" :options="roleOptions"
                            :props="{ expandTrigger: 'hover',checkStrictly:true,multiple:false,emitPath:false }"
                            clearable filterable style="width:100%">
                        </el-cascader>
                    </el-form-item>
                    <el-form-item label="备注" prop="roleDsc">
                        <el-input type="textarea" v-model="formData.roleDsc" :autosize="{ minRows: 2, maxRows: 4}"
                            placeholder="请输入备注" maxlength="200" show-word-limit></el-input>
                    </el-form-item>
                    <el-form-item style="text-align: right;">
                        <el-button type="primary" icon="el-icon-folder" @click="submitEvent('formData')"
                            :disabled="disabled" v-cloak>保存</el-button>
                        <el-button type="warning" icon="el-icon-refresh" @click="resetEvent('formData')" v-cloak>
                            重置
                        </el-button>
                        <el-button type="warning" icon="el-icon-switch-button" @click="closeEvent('formData')" v-cloak>
                            退出
                        </el-button>
                    </el-form-item>
                </el-form>
            </vxe-modal>
        </el-main>
    </el-container>
</body>
<script type="text/javascript">
    window.onload = function () {
        var main = {
            data() {
                return {
					//排序
					prop: '',
					order: '',
                    dataLoading: false,
                    loading: false,
                    disabled: false,
                    visible: false,
                    tableHeight: '100%',
                    roleOptions: [],
                    tableData: [],
                    tablePage: {
                        perfect: true,
                        total: 0,
                        currentPage: 1,
                        pageSize: 30,
                        align: 'left',
                        pageSizes: [30, 50, 100, 200],
                        layouts: ['Sizes', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump',
                            'Total'
                        ],
                    },
                    tableToolbar: {
                        id: 'toolbar',
                        size: 'mini',
                        perfect: true,
                        buttons: [],
                    },
                    tableExport: {
                        filename: 'export',
                        sheetName: 'Sheet1',
                        type: 'xlsx',
                        // 自定义类型
                        types: ['xlsx', 'csv', 'html', 'xml', 'txt']
                    },
                    tableRadio: {
                        trigger: 'row',
                        highlight: true
                    },
                    submitLoading: false,
                    selectRow: null,
                    showEdit: false,
                    queryData: {
                        keyword: ""
                    },
                    formData: {
                        roleId: "",
                        roleName: "",
                        roleDsc: "",
                        parentRoleId: ""
                    },
                    formRules: {
                        roleCode: [{
                                required: true,
                                message: '请输入角色代码'
                            },
                            {
                                min: 1,
                                max: 32,
                                message: '长度在1到32个字符'
                            }
                        ],
                        roleName: [{
                                required: true,
                                message: '请输入角色名称'
                            },
                            {
                                min: 1,
                                max: 200,
                                message: '长度在1到200个字符'
                            }
                        ],
                        sort: [{
                            required: true,
                            message: '请输入序号'
                        }]
                    }
                }
            },
            created() {
                this.findList();
                this.getBtn();
            },
            mounted() {
                this.tableHeight = window.innerHeight - this.$refs.xGrid.$el.offsetTop - 5;
            },
            methods: {
				searchEvent() {
						this.findList();
				},
				searchEventA() {
						this.queryData.keyword = "";
						this.findList();
				},
                getTreeData(data) {
                    for (let i = 0; i < data.length; i++) {
                        if (data[i].children.length < 1) {
                            // children若为空数组，则将children设为undefined
                            data[i].children = undefined;
                        } else {
                            // children若不为空数组，则继续 递归调用 本方法
                            this.getTreeData(data[i].children);
                        }
                    }
                    return data;
                },
                getBtn() {
                    this.tableToolbar.buttons = []
                    let bts = Tool.getButton()
                    let btns = []
                    this.tableToolbar.buttons = btns.concat(bts)
                },
                //分页
                handlePageChange({
                    currentPage,
                    pageSize
                }) {
                    this.tablePage.currentPage = currentPage
                    this.tablePage.pageSize = pageSize
                    this.findList()
                },
                findList() {
                    let queryParams = Object.assign({
                        page: this.tablePage.currentPage,
                        rows: this.tablePage.pageSize,
                        keyword: this.queryData.keyword,
						order:this.order,
						prop:this.prop
                    });
                    this.dataLoading = true;
                    var object = this;
                    webApi("/role/getRoleList", "post", queryParams, function (data) {
                        object.tableData = data.data.rows;
                        object.tablePage.total = data.data.total
                        object.dataLoading = false;
                        object.getRoleOptions();
                    }, function (data) {
                        object.tableData = [];
                        object.tablePage.total = 0
                        object.dataLoading = false;
                    });
                },
                getRoleOptions() {
                    let that = this;
                    webApi('/role/getRoleOptions', 'post', {}, function (data) {
                        that.roleOptions = that.getTreeData(data.data);
                    }, function (xhr, type, errorThrown) {})
                },
                searchEvent(formName, acType) {
                    if (acType == 0) {
                        this.queryData = {
                            keyword: ""
                        }
                    }
                    this.tablePage.currentPage = 1
                    this.findList()
                },
                formatDate({
                    cellValue
                }) {
                    return XEUtils.toDateString(cellValue, 'yyyy-MM-dd HH:mm:ss')
                },
                toolbarButtonClickEvent({
                    code
                }, event) {
                    switch (code) {
                        case 'reset':
                            this.searchEvent(this.queryData, 0)
                            break;
                        case 'search':
                            this.searchEvent(this.queryData, 1)
                            break;
                        case 'btnInsert':
                            var row = this.$refs.xGrid.getCheckboxRecords();
                            if (row) {
                                var parentCode = row.parentMenuId;
                            } else {
                                var parentCode = "";
                            }
                            this.insertEvent(parentCode);
                            break;
                        case 'btnUpdate':
                            if (this.$refs.xGrid.getCheckboxRecords().length == 1) {
                                let row = this.$refs.xGrid.getCheckboxRecords()
                                this.editEvent(row[0]);
                            } else if (this.$refs.xGrid.getCheckboxRecords().length > 1) {
                                this.$message({
                                    message: "数据大于一条，无法修改",
                                    type: 'warning',
                                    center: true
                                });
                            } else {
                                this.$message({
                                    message: "请选择一行数据",
                                    type: 'warning',
                                    center: true
                                });
                            }
                            break;
                        case 'btnDelete':
                            var row = this.$refs.xGrid.getCheckboxRecords();
                            console.log(row)
                            if (row.length > 0) {
                                this.removeEvent(row);
                            } else {
                                this.$message({
                                    message: "请选择需要删除的数据行",
                                    type: 'warning',
                                    center: true
                                });
                            }
                            break;
                        case 'btnExport':
                            this.$refs.xGrid.exportData({
                                filename: '菜单列表',
                                sheetName: 'Sheet1',
                                type: 'xlsx'
                            });
                            break;
                    }
                },
                insertEvent() {
                    this.formData = {
                        roleDsc: "",
                        roleId: "",
                        roleName: "",
                        parentRoleId: ""
                    };
                    this.selectRow = null;
                    this.showEdit = true;
                },
                submitEvent(formName) {
                    this.$refs[formName].validate((valid) => {
                        if (valid) {
                            this.submitLoading = true;
                            this.disabled = true;
                            this.formData.parentRoleId = this.formData.parentRoleId.toString();
                            let params = Object.assign(this.formData);
                            let that = this;
                            webApi('/role/save', 'post', params, function (data) {
                                if (data.code == 200) {
                                    that.findList();
                                    that.$message({
                                        message: data.msg,
                                        type: 'success',
                                        center: true
                                    });
                                    that.showEdit = false;
                                } else {
                                    that.$message({
                                        message: data.msg,
                                        type: 'error',
                                        center: true
                                    });
                                }
                                that.disabled = false;
                            }, function (xhr, type, errorThrown) {});
                            this.submitLoading = false;
                        } else {
                            return false;
                        }
                    });
                },
                resetEvent(formName) {
                    this.formData = {
                        parentRoleId: "",
                        roleId: "",
                        roleName: "",
                        roleDsc: ""
                    };
                    this.selectRow = null;
                },
                closeEvent(formName) {
                    this.showEdit = false;
                },
                editEvent(row) {
                    this.formData = {
                        parentRoleId: row.parentRoleId+'',
                        roleId: row.roleId,
                        roleName: row.roleName,
                        roleDsc: row.roleDsc == null ? "" : row.roleDsc
                    };
					console.log( this.formData.parentRoleId)
                    this.selectRow = row;
                    this.showEdit = true;
                },
                removeEvent(row) {
                    this.$XModal.confirm('您确定要删除该数据?(删除后可能会影响部分用户菜单按钮权限)').then(type => {
                        if (type === 'confirm') {
                            this.submitLoading = true;
                            let that = this
                            let ids = ""
                            row.forEach(item => {
                                ids += item.roleId + ","
                            });
                            let params = Object.assign({
                                roleId: ids
                            });
                            webApi('/role/delete', 'post', params, function (data) {
                                if (data.code == 200) {
                                    that.findList()
                                    that.$message({
                                        message: data.msg,
                                        type: 'success',
                                        center: true
                                    });
                                    that.showEdit = false;
                                } else {
                                    that.$message({
                                        message: data.msg,
                                        type: 'error',
                                        center: true
                                    });
                                }
                                that.disabled = false;
                            }, function (xhr, type, errorThrown) {});
                            this.submitLoading = false;
                        }
                    });
                },
                statusEvent(row, status) {
                    var msg = status == 1 ? '您确定要启用该数据？' : '您确定要停用该数据？';
                    this.$XModal.confirm(msg).then(type => {
                        if (type === 'confirm') {
                            this.submitLoading = true;
                            let params = Object.assign({
                                id: row.id,
                                status: status
                            });
                            let that = this
                            webApi('/role/setStatus', 'post', params, function (data) {
                                that.findList()
                                that.$message({
                                    message: data.msg,
                                    type: 'success',
                                    center: true
                                });
                            }, function () {})
                            this.submitLoading = false;
                        }
                    });
                },
                cellDBLClickEvent({
                    row
                }) {
                    this.editEvent(row);
                },
                checkColumnMethod({
                    column
                }) {
                    if (['roleId', 'roleName'].includes(column.property)) {
                        return false
                    }
                    return true
                },
				//表头列排序
				tableSortChange(column, prop, order) {
					//点击排序按钮后拿到column.order，可以发送column.order给后台，后台再根据什么排序来返回排序过后的数据
					console.log(column + '---' + column.prop + '---' + column.order)
					this.order=column.order;
					this.prop=column.prop;
					this.findList();
				}
            }
        };

        var vue = Vue.extend(main);
        new vue().$mount('#app');
    }
</script>

</html>